from typing import List, Optional
from ..interfaces import PlatformAdapter, NormalizedContent
from ..vendor.mindspider.media_platform.xhs.client import XiaoHongShuClient
from ..vendor.mindspider.media_platform.xhs.field import SearchSortType, SearchNoteType


class XhsAdapter(PlatformAdapter):
    def __init__(self, headers: Optional[dict] = None, proxy: Optional[str] = None, cookies: Optional[dict] = None):
        self.client = XiaoHongShuClient(headers=headers or {}, proxy=proxy, cookie_dict=cookies or {})

    async def search_by_keywords(self, keywords: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for kw in keywords:
            data = await self.client.get_note_by_keyword(kw, page=1, page_size=10, sort=SearchSortType.GENERAL, note_type=SearchNoteType.ALL)
            arr = data.get('items') or data.get('notes') or []
            for it in arr:
                card = it.get('note_card') or it
                nid = str(card.get('id') or card.get('note_id') or '')
                title = card.get('title') or ''
                desc = card.get('desc') or card.get('abstract') or ''
                user = card.get('user') or {}
                author = user.get('nickname') or user.get('name')
                url = f"https://www.xiaohongshu.com/explore/{nid}" if nid else None
                nc = NormalizedContent(platform='xhs', content_id=nid, author=author, title=title, text=desc, url=url, published_at=None, metrics={}, raw=card)
                items.append(nc)
        return items

    async def fetch_by_accounts(self, accounts: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for uid in accounts:
            try:
                notes = await self.client.get_all_notes_by_creator(uid, crawl_interval=0.5)
            except Exception:
                notes = []
            for card in notes:
                c = card.get('note_card') or card
                nid = str(c.get('id') or c.get('note_id') or '')
                title = c.get('title') or ''
                desc = c.get('desc') or c.get('abstract') or ''
                user = c.get('user') or {}
                author = user.get('nickname') or user.get('name')
                url = f"https://www.xiaohongshu.com/explore/{nid}" if nid else None
                items.append(NormalizedContent(platform='xhs', content_id=nid, author=author, title=title, text=desc, url=url, published_at=None, metrics={}, raw=c))
        return items
